import {
    createRouter,
    createWebHashHistory,
    createWebHistory
} from 'vue-router'
import store from '@/store/index.js'
import { toast, showFullLoading, hideFullLoading } from '@/utils/utils'



import Admin from '@/layouts/PugAdmin.vue'
import Index from '@/views/index.vue'
import Login from '@/views/login.vue'
import NotFound from '@/views/error-page/404.vue'
import ProductList from '@/views/product/list.vue'
import CategoryList from '@/views/category/list.vue'
import CouponList from '@/views/coupon/list.vue'
import UserList from '@/views/user/list.vue'
import OrderList from '@/views/order/list.vue'
import CommentList from '@/views/comment/list.vue'
import ImageList from '@/views/image/list.vue'
import NoticeList from '@/views/notice/list.vue'
import SettingBase from '@/views/setting/base.vue'
import LevelList from '@/views/level/list.vue'

import ManagerList from '@/views/manager/list.vue'
import RoleList from '@/views/role/list.vue'
import PermissionList from '@/views/permission/list.vue'
import DistributionList from '@/views/distribution/list.vue'
import DistributionSetting from '@/views/distribution/setting.vue'
import SettingPay from '@/views/setting/pay.vue'




const routes = [{
        path: '/',
        name: "admin",
        component: Admin
    },
    {
        path: '/login',
        name: "/login",
        meta: { title: '登录' },
        component: Login
    },
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        meta: { title: '404' },
        component: NotFound
    }
];


// 动态路由，用于匹配菜单动态添加路由
const asyncRoutes = [{
    path: '/',
    name: "/",
    meta: { title: '后台首页' },
    component: Index
}, {
    path: '/user/list',
    name: "/user/list",
    meta: { title: '用户管理' },
    component: UserList
}, {
    path: '/manager/list',
    name: "/manager/list",
    meta: { title: '后台管理员' },
    component: ManagerList
}, {
    path: '/role/list',
    name: "/role/list",
    meta: { title: '角色管理' },
    component: RoleList
}, {
    path: '/permission/list',
    name: "/permission/list",
    meta: { title: '权限管理' },
    component: PermissionList
}, {
    path: '/user/list',
    name: "/user/list",
    meta: { title: '用户管理' },
    component: UserList
}, {
    path: '/distribution/list',
    name: "/distribution/list",
    meta: { title: '分销管理' },
    component: DistributionList
}, {
    path: '/distribution/setting',
    name: "/distribution/setting",
    meta: { title: '分销设置' },
    component: DistributionSetting
}, {
    path: '/setting/pay',
    name: "/setting/pay",
    meta: { title: '支付设置' },
    component: SettingPay
}, {
    path: '/level/list',
    name: "/level/list",
    meta: { title: '会员等级' },
    component: LevelList
}, {
    path: "/category/list",
    name: "/category/list",
    component: CategoryList,
    meta: { title: "分类列表" }
}, {
    path: "/coupon/list",
    name: "/coupon/list",
    component: CouponList,
    meta: { title: "优惠券管理" }
}, {
    path: "/order/list",
    name: "/order/list",
    component: OrderList,
    meta: {
        title: "订单列表"
    }
}, {
    path: "/comment/list",
    name: "/comment/list",
    component: CommentList,
    meta: {
        title: "评价列表"
    }
}, {
    path: "/image/list",
    name: "/image/list",
    component: ImageList,
    meta: {
        title: "图库列表"
    }
}, {
    path: "/notice/list",
    name: "/notice/list",
    component: NoticeList,
    meta: {
        title: "公告列表"
    }
}, {
    path: "/setting/base",
    name: "/setting/base",
    component: SettingBase,
    meta: {
        title: "配置"
    }
}, {
    path: '/product/list',
    name: "/product/list",
    meta: { title: '产品列表' },
    component: ProductList
}, {
    path: '/distribution/index',
    name: "/distribution/index",
    meta: { title: '产品列表' },
    component: ProductList
}, {
    path: '/distribution/setting',
    name: "/distribution/setting",
    meta: { title: '产品列表' },
    component: ProductList
}];


export const router = createRouter({
    linkActiveClass: "active",
    history: createWebHashHistory(),
    scrollBehavior(to, from, savedPosition) {
        return { top: 0, left: 0 }
    },
    routes
})


// 动态注册路由方法
export function registerRoutes(menuList) {
    // 是否有新的路由
    let hasNewRoutes = false
    const findAndAddRoutesByMenus = (arr) => {
        arr.forEach(e => {
            let item = asyncRoutes.find(o => o.path == e.path)
            if (item && !router.hasRoute(item.path)) {
                router.addRoute("admin", item)
                hasNewRoutes = true
            }
            if (e.children && e.children.length > 0) {
                findAndAddRoutesByMenus(e.children)
            }
        })
    }

    findAndAddRoutesByMenus(menuList)

    return hasNewRoutes
}

let loadNewRoute = false;
//4：判断目标路由是否是/login，如果是，则直接返回true
router.beforeEach(async(to, from, next) => {
    showFullLoading()

    // 判断是否已经登录
    var token = store.getters["login/isLogin"];

    // 没有登录，强制跳转回登录页
    if (!token && to.path != "/login") {
        toast("请先登录", "error")
        return next({ path: "/login" })
    }

    // 防止重复登录
    if (token && to.path == "/login") {
        toast("请勿重复登录", "error")
        return next({ path: from.path ? from.path : "/" })
    }

    // 如果用户登录了，自动获取用户信息，并存储在vuex当中
    let hasNewRoute = false;
    if (token && !loadNewRoute) {
        if (to.path != '/login') {

            // 追加到到菜单
            store.commit("menu/addMenu", {
                title: to.meta.title,
                path: to.path,
                params: to.params,
                active: true
            });
        }

        // 获取状态管理的菜单信息，登录的时候已经请求放入了状态管理中了
        let menusList = await store.dispatch("menu/asyncGetMenuList")
            // 锁住
        loadNewRoute = true;
        // 注册路由
        hasNewRoute = registerRoutes(menusList);
    }

    hasNewRoute ? next(to.fullPath) : next();
});


// 设置标题
router.afterEach((to) => {
    hideFullLoading();
    document.title = to.meta.title + "-PugAdmin" || "PugAdmin";
})